package com.ruoyi.web.controller.common;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.spec.AlgorithmParameterSpec;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.ruoyi.common.utils.ALiYunSms;
import com.ruoyi.common.utils.BaiDuSms;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * app请求处理
 * 
 * @author ruoyi
 */
@Api("app接口管理")
@RestController
@RequestMapping("/app")
public class AppController extends BaseController{

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IIntegralService integralService;
    @Autowired
    private ICustomerService customerService;
	@Autowired
	private ICashService cashService;
	@Autowired
	private IShareService shareService;
	@Autowired
	private ISignService signService;
    @Autowired
    private IRelationshipRecordService relationshipRecordService;
	@Autowired
	private ISmsLogService smsLogService;
	@Autowired
	private IAddressService addressService;
	@Autowired
	private INewsService newsService;
	@Autowired
	private ICollectService collectService;
	@Autowired
	private IFeedbackService feedbackService;
	@Autowired
	private ISysDictDataService dictDataService;
	@Autowired
	private IMessageService messageService;
	@Autowired
	private IPosterService posterService;

    /**
     * 业务员
     */

    @ApiOperation("查询业务员列表")
    @PostMapping("/getMemberList")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "pid", value = "pid", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "realName", value = "真实姓名", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
    })
    @ResponseBody
    public AjaxResult getMemberList(@RequestParam(value="pid", required=false) String pid,
    								@RequestParam(value="realName", required=false) String realName,
    								@RequestParam int pageNum,
    								@RequestParam int pageSize) throws Exception{
    	 Member member = new Member();
    	 if(pid!=null && !pid.equals("")){
    		 member.setPid(Long.parseLong(pid));
    	 }
    	 if(realName!=null && !realName.equals("")){
    		 member.setRealName(realName);
    	 }
    	 String orderBy = "create_time desc";
    	 PageHelper.startPage(pageNum, pageSize, orderBy);
         List<Member> list = memberService.selectMemberList(member);
        try{
        	AjaxResult ajax = AjaxResult.success();
        	ajax.put("count", new PageInfo<Member>(list).getTotal());
        	ajax.put("data", list);
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @ApiOperation("通过openid查询业务员详情")
    @PostMapping("/getMemberByOpenId")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "openId", value = "openId", required = true, dataType = "string", paramType = "query"),
    })
    @ResponseBody
    public AjaxResult getMemberByOpenId(@RequestParam String openId) throws Exception{

		Member member =  new Member();
    	member.setOpenId(openId);
        try{
        	List<Member> selectMemberList = memberService.selectMemberList(member);
        	AjaxResult ajax = AjaxResult.success();
        	if(selectMemberList.size()>0){
            	ajax.put("data", selectMemberList.get(0));
        	}else{
        		ajax.put("data", null);
        	}
        	return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @ApiOperation("查询业务员详情")
    @PostMapping("/getMember")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "query"),
    })
    @ResponseBody
    public AjaxResult getMember(@RequestParam long id) throws Exception{
    	Member member =  memberService.selectMemberById(id);
        try{
            return AjaxResult.success(member);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @ApiOperation("新增业务员")
    @PostMapping("/addMember")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "nickName", value = "昵称", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "realName", value = "真实姓名", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "telephone", value = "手机号", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "birthday", value = "生日", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "email", value = "邮箱", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "cover", value = "头像", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "address", value = "联系地址", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "remark", value = "补充情况", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "userType", value = "用户类型", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "integralCount", value = "积分值", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pid", value = "pid", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "card", value = "名片", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string", paramType = "header")

    })
    @ResponseBody
    public AjaxResult addMember(@RequestParam String nickName,
    							  @RequestParam(value="realName", required=false) String realName,
    							  @RequestParam String telephone,
								 @RequestParam(value="sex", required=false) String sex,
								 @RequestParam(value="birthday", required=false) String birthday,
								 @RequestParam(value="email", required=false) String email,
								 @RequestParam(value="cover", required=false) String cover,
    							  @RequestParam(value="address", required=false) String address,
    							  @RequestParam(value="remark", required=false) String remark,
    							  @RequestParam String openId,
    							  @RequestParam Integer userType,
    							  @RequestParam(value="integralCount", required=false) String integralCount,
    							  @RequestParam(value="pid", required=false) String pid,
								  @RequestParam(value="card", required=false) String card,
								  @RequestHeader String token) throws Exception{
		if(token.length()<13 || !Md5Utils.hash("mude2020"+token.substring(0,13)).equals(token.substring(13))){
			return AjaxResult.error("访问出错");
		}
		/*if(true){
			return AjaxResult.error("系统维护中");
		}*/
		 Member member = new Member();
		 member.setOpenId(openId);
		 AjaxResult ajax = AjaxResult.success();
		 List<Member> mems = memberService.selectMemberList(member);
		 if(mems.size()>0){
			ajax.put("code", 0);
			return ajax;
		 }
		 if(nickName!=null && !nickName.equals("")){
    		 member.setNickName(nickName);
    	 }
    	 if(realName!=null && !realName.equals("")){
    		 member.setRealName(realName);
    	 }
    	 if(telephone!=null && !telephone.equals("")){
    		 member.setTelephone(telephone);
    	 }
		 if(sex!=null && !sex.equals("")&& !sex.equals("null")){
			member.setSex(Integer.parseInt(sex));
		 }
		 if(birthday!=null && !birthday.equals("")){
			member.setBirthday(birthday);
		 }
		 if(email!=null && !email.equals("")){
			member.setEmail(email);
		 }
    	 if(cover!=null && !cover.equals("")){
    		 member.setCover(cover);
    	 }
    	 if(address!=null && !address.equals("")){
    		 member.setAddress(address);
    	 }
    	 if(remark!=null && !remark.equals("")){
    		 member.setRemark(remark);
    	 }
		if(card!=null && !card.equals("")){
			member.setCard(card);
		}
		 member.setStatus(0);
		 member.setSignStatus(0);
		 member.setVipType(1);
		 member.setUserType(userType);
    	 if(integralCount!=null && !integralCount.equals("")){
        	 member.setIntegralCount(Integer.parseInt(integralCount));
    	 }else{
    		 member.setIntegralCount(0);
    	 }
    	 if(pid!=null && !pid.equals("")){
    	 	 Member pmember = memberService.selectMemberById(Long.parseLong(pid));
    	 	 if(pmember!=null&&pmember.getStatus()==0){
				 member.setPid(Long.parseLong(pid));
			 }else{
				 member.setUserType(1);
			 }
    	 }
     	 ajax.put("code", memberService.insertMember(member));
     	 ajax.put("data", member);

		if(integralCount!=null && !integralCount.equals("")){
			Integral integral = new Integral();
			integral.setIntegralCount(Integer.parseInt(integralCount));
			integral.setReason("新用户成功注册获得积分");
			integral.setType(3);
			integral.setMemberId(member.getId());
			integralService.insertIntegral(integral);
		}

     	 //邀请注册增加积分
		/*if(pid!=null && !pid.equals("")){
			int changeIntegral = 30;
			Member pMember = memberService.selectMemberById(Long.parseLong(pid));
			pMember.setIntegralCount(pMember.getIntegralCount()+changeIntegral);
			memberService.updateMember(pMember);
			Integral integral = new Integral();
			integral.setIntegralCount(changeIntegral);
			integral.setReason("邀请用户("+nickName+")成功注册获得积分");
			integral.setType(1);
			integral.setMemberId(Long.parseLong(pid));
			integral.setMemberCid(member.getId());
			integralService.insertIntegral(integral);
		}*/
         return ajax;
    }
    
    @ApiOperation("修改业务员")
    @PostMapping("/editMember")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "业务员id", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "nickName", value = "昵称", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "realName", value = "真实姓名", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "telephone", value = "手机号", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "birthday", value = "生日", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "email", value = "邮箱", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "cover", value = "头像", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "address", value = "联系地址", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "remark", value = "补充情况", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "integralCount", value = "积分值", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pid", value = "pid", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "card", value = "card", required = false, dataType = "string", paramType = "query")

    })
    @ResponseBody
    public AjaxResult editMember(@RequestParam long id,
    							 @RequestParam(value="nickName", required=false) String nickName,
    							 @RequestParam(value="realName", required=false) String realName,
    							 @RequestParam(value="telephone", required=false) String telephone,
								 @RequestParam(value="sex", required=false) String sex,
								 @RequestParam(value="birthday", required=false) String birthday,
								 @RequestParam(value="email", required=false) String email,
    							 @RequestParam(value="cover", required=false) String cover,
								 @RequestParam(value="address", required=false) String address,
    							 @RequestParam(value="remark", required=false) String remark,
    							 @RequestParam(value="integralCount", required=false) String integralCount,
    							 @RequestParam(value="pid", required=false) String pid,
								 @RequestParam(value="card", required=false) String card) throws Exception{
    	 Member member =  memberService.selectMemberById(id);
    	 if(nickName!=null && !nickName.equals("")){
    		 member.setNickName(nickName);
    	 }
    	 if(realName!=null && !realName.equals("null")){
    		 member.setRealName(realName);
    	 }
    	 if(telephone!=null && !telephone.equals("")){
    		 member.setTelephone(telephone);
    	 }
		 if(sex!=null && !sex.equals("") && !sex.equals("null")){
			member.setSex(Integer.parseInt(sex));
		 }
		 if(birthday!=null && !birthday.equals("null")){
			member.setBirthday(birthday);
		 }
		 if(email!=null && !email.equals("null")){
			member.setEmail(email);
		 }
    	 if(cover!=null && !cover.equals("null")){
    		 member.setCover(cover);
    	 }
		 if(address!=null && !address.equals("null")){
			 member.setAddress(address);
		 }
    	 if(remark!=null && !remark.equals("null")){
    		 member.setRemark(remark);
    	 }
		if(card!=null && !card.equals("null")){
			 member.setCard(card);
		}
    	 if(integralCount!=null && !integralCount.equals("")){
        	 member.setIntegralCount(Integer.parseInt(integralCount));
    	 }
    	 if(pid!=null && !pid.equals("")){
        	 member.setPid(Long.parseLong(pid));
    	 }
     	 AjaxResult ajax = AjaxResult.success();
     	 ajax.put("code", memberService.updateMember(member));
     	 ajax.put("data", member);
         return ajax;
    }
    
    /**
     * 积分记录
     */
    
    
    @ApiOperation("查询积分记录列表")
    @PostMapping("/getIntegralList")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
    })
    @ResponseBody
    public AjaxResult getIntegralList(@RequestParam long memberId,
									  @RequestParam(value="type", required=false) String type,
    								  @RequestParam int pageNum,
    								  @RequestParam int pageSize) throws Exception{
    	 Integral integral = new Integral();
    	 integral.setMemberId(memberId);
    	 if(StringUtils.isNotBlank(type)){
			 integral.setType(Integer.parseInt(type));
		 }
    	 String orderBy = "create_time desc";
    	 PageHelper.startPage(pageNum, pageSize, orderBy);
         List<Integral> list = integralService.selectIntegralList(integral);
        try{
        	AjaxResult ajax = AjaxResult.success();
        	ajax.put("count", new PageInfo<Integral>(list).getTotal());
        	ajax.put("data", list);
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    
    
    /**
     * 客户
     */
    
    @ApiOperation("查询客户详情")
    @PostMapping("/getCustomer")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "shareType", value = "分享类型", required = false, dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),
	})
    @ResponseBody
    public AjaxResult getCustomer(@RequestParam long id,
									@RequestParam(value="shareType", required=false) String shareType,
									@RequestParam(value="memberId", required=false) String memberId) throws Exception{
    	Customer customer =  customerService.selectCustomerById(id);
		if(StringUtils.isNotBlank(shareType)&&shareType.equals("1")) {
			Share share = new Share();
			if(memberId!=null && !memberId.equals("")){
				share.setCustomerId(id);
				share.setMemberId(Long.parseLong(memberId));
				List<Share> list = shareService.selectShareList(share);
				if(list.size()>0){
					customer.setIdentification(list.get(0).getIdentification());
				}
			}
		}
        try{
            return AjaxResult.success(customer);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @ApiOperation("查询客户列表")
    @PostMapping("/getCustomerList")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "type", value = "分享类型", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "name", value = "客户姓名", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
    })
    @ResponseBody
    public AjaxResult getCustomerList(@RequestParam String type,
									  @RequestParam String memberId,
    								  @RequestParam(value="name", required=false) String name,
    								  @RequestParam int pageNum,
    								  @RequestParam int pageSize) throws Exception{
    	if(StringUtils.isNotBlank(type)&&type.equals("1")){
			Share share = new Share();
			if(memberId!=null && !memberId.equals("")){
				share.setMemberId(Long.parseLong(memberId));
			}
			String orderBy = "create_time desc";
			PageHelper.startPage(pageNum, pageSize, orderBy);
			List<Share> list = shareService.selectShareList(share);
			for(Share se:list){
				Customer customer = customerService.selectCustomerById(se.getCustomerId());
				if(customer!=null){
					se.setId(customer.getId());
					se.setName(customer.getName());
					se.setTelephone(customer.getTelephone());
					se.setAddress(customer.getAddress());
					se.setCompany(customer.getCompany());
					se.setIdentificationAdmin(customer.getIdentificationAdmin());
					se.setArea(customer.getArea());
					se.setType(customer.getType());
					se.setDescription(customer.getDescription());
					se.setRemark(customer.getRemark());
				}
			}
			try{
				AjaxResult ajax = AjaxResult.success();
				ajax.put("count", new PageInfo<Share>(list).getTotal());
				ajax.put("data", list);
				return ajax;
			}catch (Exception e){
				return AjaxResult.error(e.getMessage());
			}
		}else{
			Customer customer = new Customer();
			if(memberId!=null && !memberId.equals("")){
				customer.setMemberId(Long.parseLong(memberId));
			}
			if(name!=null && !name.equals("")){
				customer.setName(name);
			}
			String orderBy = "create_time desc";
			PageHelper.startPage(pageNum, pageSize, orderBy);
			List<Customer> list = customerService.selectCustomerList(customer);

			try{
				AjaxResult ajax = AjaxResult.success();
				ajax.put("count", new PageInfo<Customer>(list).getTotal());
				ajax.put("data", list);
				return ajax;
			}catch (Exception e){
				return AjaxResult.error(e.getMessage());
			}
		}
    }

	@ApiOperation("新增联系记录")
	@PostMapping("/addRecord")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "relationshipTime", value = "联系时间", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "relationshipUser", value = "联系人", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "relationshipResult", value = "联系结果", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "relationshipRemark", value = "备注", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "customerId", value = "客户id", required = true, dataType = "int", paramType = "query")

	})
	@ResponseBody
	public AjaxResult addRecord(@RequestParam String relationshipTime,
								  @RequestParam String relationshipUser,
								  @RequestParam String relationshipResult,
								  @RequestParam(value="relationshipRemark", required=false) String relationshipRemark,
								  @RequestParam long customerId) throws Exception{

		RelationshipRecord relationshipRecord = new RelationshipRecord();
		AjaxResult ajax = AjaxResult.success();

		if(relationshipTime!=null && !relationshipTime.equals("") && !relationshipTime.equals("null")){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = null;
			try {
				date = format.parse(relationshipTime);
				relationshipRecord.setRelationshipTime(date);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(relationshipUser!=null && !relationshipUser.equals("") && !relationshipUser.equals("null")){
			relationshipRecord.setRelationshipUser(relationshipUser);
		}
		if(relationshipResult!=null && !relationshipResult.equals("") && !relationshipResult.equals("null")){
			relationshipRecord.setRelationshipResult(relationshipResult);
		}
		if(relationshipRemark!=null && !relationshipRemark.equals("") && !relationshipRemark.equals("null")){
			relationshipRecord.setRelationshipRemark(relationshipRemark);

		}
		relationshipRecord.setCustomerId(customerId);

		Customer customer = customerService.selectCustomerById(relationshipRecord.getCustomerId());
		customer.setRelationTime(DateUtils.getNowDate());
		customerService.updateCustomer(customer);

		ajax.put("code", relationshipRecordService.insertRelationshipRecord(relationshipRecord));
		ajax.put("data", relationshipRecord);
		return ajax;
	}

    @ApiOperation("新增客户")
    @PostMapping("/addCustomer")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "name", value = "客户姓名", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "telephone", value = "客户手机号", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "address", value = "详细地址", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "company", value = "公司名称", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "area", value = "面积", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "identification", value = "标识", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "remark", value = "补充情况", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query")

    })
    @ResponseBody
    public AjaxResult addCustomer(@RequestParam String name,
    							  @RequestParam String telephone,
    							  @RequestParam(value="address", required=false) String address,
								  @RequestParam(value="company", required=false) String company,
    							  @RequestParam(value="identification", required=false) String identification,
    							  @RequestParam(value="remark", required=false) String remark,
    							  @RequestParam(value="area", required=false) String area,
    							  @RequestParam Integer type,
    							  @RequestParam long memberId) throws Exception{

		Customer customer = new Customer();
		AjaxResult ajax = AjaxResult.success();
		if(telephone!=null && !telephone.equals("")){
			String[] telephones = telephone.split(";");
			String teleStr = "";
			for(String tele: telephones) {
				customer.setTelephone(tele);
				List<Customer> cuss = customerService.selectCustomerList(customer);
				if (cuss.size() > 0) {
					teleStr += tele+",";
				}
			}
			if(StringUtils.isNotBlank(teleStr)) {
				ajax.put("code", 0);
				ajax.put("msg", "该客户手机号:"+teleStr.substring(0,teleStr.length()-1)+"已存在！");
				return ajax;
			}
			customer.setTelephone(telephone);
    	 }else{
			ajax.put("code", 0);
			return ajax;
		 }
		 if(name!=null && !name.equals("")){
			 customer.setName(name);
		 }
    	 if(address!=null && !address.equals("") && !address.equals("null")){
    		 customer.setAddress(address);
    	 }
		if(company!=null && !company.equals("") && !address.equals("company")){
			customer.setCompany(company);
		}
		 if(identification!=null && !identification.equals("") && !identification.equals("null")){
			customer.setIdentification(Integer.parseInt(identification));
		 }
    	 if(remark!=null && !remark.equals("") && !remark.equals("null")){
    		 customer.setRemark(remark);
    	 }
    	 if(area!=null && !area.equals("") && !area.equals("null")){
    		 customer.setArea(area);
    	 }
    	 if(type!=null && type!=-1){
    		 customer.setType(type);
    	 }
    	 customer.setMemberId(memberId);
		 customer.setRelationTime(DateUtils.getNowDate());
	     ajax.put("code", customerService.insertCustomer(customer));
     	 ajax.put("data", customer);
         return ajax;
    }

    @ApiOperation("修改客户")
    @PostMapping("/editCustomer")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "客户id", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "name", value = "客户姓名", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "telephone", value = "客户手机号", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "address", value = "详细地址", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "company", value = "公司名称", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "identification", value = "标识", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "remark", value = "补充情况", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "area", value = "面积", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "shareType", value = "分享类型", required = false, dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),

    })
    @ResponseBody
    public AjaxResult editCustomer(@RequestParam long id,
    							  @RequestParam(value="name", required=false) String name,
    							  @RequestParam(value="telephone", required=false) String telephone,
    							  @RequestParam(value="address", required=false) String address,
    							  @RequestParam(value="company", required=false) String company,
    							  @RequestParam(value="identification", required=false) String identification,
    							  @RequestParam(value="remark", required=false) String remark,
    							  @RequestParam(value="area", required=false) String area,
    							  @RequestParam(value="type", required=false) Integer type,
								   @RequestParam(value="shareType", required=false) String shareType,
								   @RequestParam(value="memberId", required=false) String memberId) throws Exception{
		Customer customer = customerService.selectCustomerById(id);
		String oldTelephone = customer.getTelephone();
		AjaxResult ajax = AjaxResult.success();
		if(telephone!=null && !telephone.equals("")){
			 String[] telephones = telephone.split(";");
			 String[] oldTelephones = oldTelephone.split(";");
			 List<String> oldTelephoneList = Arrays.asList(oldTelephones);
			 String teleStr = "";
			 for(String tele: telephones) {
				 if(oldTelephoneList.contains(tele)){
					 continue;
				 }
				 customer.setTelephone(tele);
				 List<Customer> cuss = customerService.selectCustomerList(customer);
				 if(!oldTelephone.equals(telephone)&&cuss.size()>0){
					 teleStr += tele+",";
				 }
			 }
			 if(StringUtils.isNotBlank(teleStr)) {
				ajax.put("code", 0);
				ajax.put("msg", "该客户手机号:"+teleStr.substring(0,teleStr.length()-1)+"已存在！");
				return ajax;
			 }
			 customer.setTelephone(telephone);
    	 }else{
			ajax.put("code", 0);
			return ajax;
		 }
		 if(name!=null && !name.equals("")){
			 customer.setName(name);
		 }
    	 if(address!=null && !address.equals("null")){
    		 customer.setAddress(address);
    	 }
		if(company!=null && !company.equals("null")){
			customer.setCompany(company);
		}
    	 if(remark!=null && !remark.equals("null")){
			 customer.setRemark(remark);
		 }
		if(area!=null && !area.equals("null")){
			customer.setArea(area);
		}
		if(type!=null && type!=-1){
			customer.setType(type);
		}
		if(StringUtils.isNotBlank(shareType)&&shareType.equals("1")) {
			Share share = new Share();
			if(memberId!=null && !memberId.equals("")){
				share.setCustomerId(id);
				share.setMemberId(Long.parseLong(memberId));
				List<Share> list = shareService.selectShareList(share);
				if(list.size()>0){
					share = list.get(0);
					if(identification!=null && !identification.equals("") && !identification.equals("null")){
						share.setIdentification(Integer.parseInt(identification));
						shareService.updateShare(share);
					}
				}
			}
		}else{
			if(identification!=null && !identification.equals("") && !identification.equals("null")){
				customer.setIdentification(Integer.parseInt(identification));
			}
		}
		 customer.setRelationTime(DateUtils.getNowDate());
		 ajax.put("code", customerService.updateCustomer(customer));
     	 ajax.put("data", customer);
         return ajax;
    }
    
    
    /**
     * 联系记录
     */
    
    
    @ApiOperation("查询联系记录列表")
    @PostMapping("/getRelationshipRecordList")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "customerId", value = "客户id", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "name", value = "联系人", required = false, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
    })
    @ResponseBody
    public AjaxResult getCustomerList(@RequestParam long customerId,
    								  @RequestParam(value="name", required=false) String name,
    								  @RequestParam int pageNum,
    								  @RequestParam int pageSize) throws Exception{
    	 RelationshipRecord relationshipRecord = new RelationshipRecord();
		 relationshipRecord.setCustomerId(customerId);
    	 if(name!=null && !name.equals("")){
    		 relationshipRecord.setRelationshipUser(name);
    	 }
    	 String orderBy = "create_time desc";
    	 PageHelper.startPage(pageNum, pageSize, orderBy);
         List<RelationshipRecord> list = relationshipRecordService.selectRelationshipRecordList(relationshipRecord);
        try{
        	AjaxResult ajax = AjaxResult.success();
        	ajax.put("count", new PageInfo<RelationshipRecord>(list).getTotal());
        	ajax.put("data", list);
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

	@ApiOperation("申请提现")
	@PostMapping("/applyCash")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "realName", value = "真实姓名", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "bankName", value = "开户银行", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "cardNum", value = "银行卡号", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "alipayNum", value = "支付宝账号", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "wxNum", value = "微信账号", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "money", value = "提现金额", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query")

	})
	@ResponseBody
	public AjaxResult applyCash( @RequestParam(value="realName", required=false) String realName,
								  @RequestParam(value="bankName", required=false) String bankName,
								  @RequestParam(value="cardNum", required=false) String cardNum,
								  @RequestParam(value="alipayNum", required=false) String alipayNum,
								  @RequestParam(value="wxNum", required=false) String wxNum,
								  @RequestParam String money,
								  @RequestParam long type,
								  @RequestParam long memberId) throws Exception{
		Cash cash = new Cash();
		if(type==0){
			cash.setRealName(realName);
			cash.setBankName(bankName);
			cash.setCardNum(cardNum);
		}else if(type==1){
			cash.setAlipayNum(alipayNum);
		}else{
			cash.setWxNum(wxNum);
		}
		cash.setStatus(0l);
		cash.setMoney(money);
		cash.setType(type);
		cash.setMemberId(memberId);

		//抵扣积分
		int changeIntegral = Integer.parseInt(money);
		Member member = memberService.selectMemberById(memberId);
		member.setIntegralCount(member.getIntegralCount()-changeIntegral);
		memberService.updateMember(member);
		Integral integral = new Integral();
		integral.setIntegralCount(-changeIntegral);
		integral.setReason("申请提现抵消积分");
		integral.setType(2);
		integral.setMemberId(memberId);
		integralService.insertIntegral(integral);

		try {
			ALiYunSms.sendSms(member.getTelephone(), member.getNickName(), "减少", money);
//			BaiDuSms.sendSms(member.getTelephone(), member.getNickName(), "减少", money);
		} catch (Exception e) {
			e.printStackTrace();
		}

		AjaxResult ajax = AjaxResult.success();
		ajax.put("code", cashService.insertCash(cash));
		ajax.put("data", cash);
		return ajax;
	}


    
    /**
     * 上传请求
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            //String url = serverConfig.getUrl() + fileName;
            String url = "https://www.e-160.com" + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    
    /**
     * 向指定URL发送请求
     */
    @ApiOperation("发送get请求")
    @PostMapping("/sendUrl")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "url", value = "发送请求的URL", required = true, dataType = "string", paramType = "query"),
    	@ApiImplicitParam(name = "params", value = "请求参数", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "method", value = "请求方式", required = false, dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "responseType", value = "响应方式", required = false, dataType = "string", paramType = "query"),
	})
    @ResponseBody
    public AjaxResult sendUrl(@RequestParam String url,
    						 @RequestParam(value="params", required=false) String params,
							 @RequestParam(value="method", required=false) String method,
							 @RequestParam(value="responseType", required=false) String responseType) throws Exception{
			HttpURLConnection conn = null;
			PrintWriter writer = null;
			String result = "";
			try{
				if(method!=null &&method.toUpperCase().equals("GET") && !url.endsWith("?")){
					url = url+"?";
				}
				if(method==null||method.equals("")){
					method = "get";
				}
				//创建URL对象
				URL urlStr = new URL(url);
				//获取URL连接
				conn = (HttpURLConnection) urlStr.openConnection();
				//设置通用请求属性
				conn.setRequestMethod(method.toUpperCase());
				conn.setRequestProperty("accept", "*/*");
				conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
				conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
				conn.setRequestProperty("Content-Type", "application/json");
				if(null!=method && "POST".equals(method.toUpperCase())){
					conn.setDoOutput(true);
					conn.setDoInput(true);
				}
				//建立实际的连接
				conn.connect();
				if(null!=method && "POST".equals(method.toUpperCase())){
					//将请求参数写入请求字符流中
					writer = new PrintWriter(conn.getOutputStream());
					writer.print(params);
					writer.flush();
				}
				//读取响应的内容
				Reader reader = null;
				StringBuilder content = new StringBuilder();
				FileOutputStream fos = null;
				try{
					if(responseType!=null && responseType.equals("arraybuffer")){
						String filePath = Global.getUploadPath();
						String fileName = "/uploadPath/wxacode/"+DateUtils.datePath()+"/"+DateUtils.dateTimeNow()+".png";
						File file = new File(filePath+fileName);
						if (!file.getParentFile().exists()){
							file.getParentFile().mkdirs();
						}
						fos = new FileOutputStream(file);
						byte[] buf = new byte[1024*8];
						int len = -1;
						while ((len = conn.getInputStream().read(buf)) != -1){
							fos.write(buf, 0, len);
						}
						fos.flush();
						result = "/profile/upload"+fileName;
					}else{
						reader = new InputStreamReader(conn.getInputStream());
						char[] buffer = new char[1024];
						int head = 0;
						while( (head=reader.read(buffer))>0 ){
							content.append(new String(buffer, 0, head));
						}
						result =  content.toString();
					}
				}finally{
					if(null!=conn.getInputStream()) conn.getInputStream().close();
					if(null!=reader) reader.close();
					if(null!=fos) fos.close();
				}
			}finally{
				if(null!=conn) conn.disconnect();
				if(null!=writer) writer.close();
			}
    	AjaxResult ajax = AjaxResult.success();
        ajax.put("data", result);
    	return ajax;
    }

	/**
	 * 客户
	 */

	@ApiOperation("获取手机号解密")
	@PostMapping("/getPhoneDecode")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "iv", value = "iv", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "sessionKey", value = "sessionKey", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getPhoneDecode(@RequestParam String iv,
									  @RequestParam String encryptedData,
									  @RequestParam String sessionKey) throws Exception{

		String decode = "";
		byte[] encrypData = Base64.decodeBase64(encryptedData);
		byte[] ivData = Base64.decodeBase64(iv);
		byte[] sessionKeyData = Base64.decodeBase64(sessionKey);
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(sessionKeyData, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		decode =  new String(cipher.doFinal(encrypData),"UTF-8");
		try{
			return AjaxResult.success(decode);
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}


	@ApiOperation("获取手机号验证码")
	@PostMapping("/sendSmsCode")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "telephone", value = "phone", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult sendSmsCode(@RequestParam String telephone, @RequestHeader String token) throws Exception{
		if(token.length()<13 || !Md5Utils.hash("mude2020"+token.substring(0,13)).equals(token.substring(13))){
			return AjaxResult.error("访问出错");
		}
		Member member = new Member();
		member.setTelephone(telephone);
		List<Member> mems = memberService.selectMemberList(member);
		if(mems.size()>0){
			AjaxResult ajax = AjaxResult.success();
			ajax.put("type", 0);
			return ajax;
		}

		SmsLog smsLog = new SmsLog();
		smsLog.setTelephone(telephone);
		smsLog.setCreateDay(DateUtils.getDate());
		List<SmsLog> smsLogs = smsLogService.selectSmsLogList(smsLog);
		if(smsLogs.size()>=5){
			AjaxResult ajax = AjaxResult.success();
			ajax.put("type", 1);
			return ajax;
		}else{
			smsLogService.insertSmsLog(smsLog);
		}

		String symbols = "0123456789";
		String code = new String();
		for(int i=0;i<6;i++){
			char ch=symbols.charAt(new Random().nextInt(symbols.length()));
			code+=ch;
		}
		try {
			String result = ALiYunSms.sendSmsCode(telephone, code);
//			String result = BaiDuSms.sendSmsCode(telephone, code);
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", result);
			ajax.put("codeVal", code);
			return ajax;
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
	}


	@ApiOperation("查询签到列表")
	@PostMapping("/getSignList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getSignList(@RequestParam String memberId,
									  @RequestParam int pageNum,
									  @RequestParam int pageSize) throws Exception{
		AjaxResult ajax = AjaxResult.success();
		Sign sign = new Sign();
		sign.setMemberId(Long.parseLong(memberId));
		String orderBy = "create_day desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<Sign> list = signService.selectSignList(sign);
		try{
			List<String> daysBetwwen = DateUtils.getDaysBetwwen(1);
			long sumCount = 0;
			if(list.size()>0){
				if(list.get(0).getCreateDay().equals(daysBetwwen.get(0))){
					if(list.get(0).getDayNum()==5){
						sumCount = 0;
					}else{
						sumCount = list.get(0).getDayNum();
					}
				}else if(list.get(0).getCreateDay().equals(daysBetwwen.get(1))){
					sumCount = list.get(0).getDayNum();
				}
			}
			ajax.put("count", new PageInfo<Sign>(list).getTotal());
			ajax.put("sumCount", sumCount);
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("新增签到")
	@PostMapping("/addSign")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sumCount", value = "签到天数", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "createDay", value = "签到日", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query")

	})
	@ResponseBody
	public AjaxResult addSign(@RequestParam int sumCount,
							  @RequestParam String createDay,
							  @RequestParam long memberId) throws Exception{
		AjaxResult ajax = AjaxResult.success();
		Member member = memberService.selectMemberById(memberId);
		if(member.getSignStatus()!=0){
			ajax.put("code", 0);
			ajax.put("msg", "签到功能已被禁用！");
			return ajax;
		}
		Sign sign = new Sign();
		sign.setCreateDay(createDay);
		sign.setMemberId(memberId);
		sign.setDayNum(Long.valueOf(sumCount+1));
		List<Sign> signs = signService.selectSignList(sign);
		if(signs.size()>0){
			ajax.put("code", 0);
			return ajax;
		}
		ajax.put("code", signService.insertSign(sign));
		ajax.put("data", sign);

		Integer integralCount = sumCount+1;
		Member selectMemberById = memberService.selectMemberById(memberId);
		selectMemberById.setIntegralCount(selectMemberById.getIntegralCount()+integralCount);
		memberService.updateMember(selectMemberById);
		Integral integral = new Integral();
		integral.setIntegralCount(integralCount);
		integral.setMemberId(memberId);
		integral.setReason("签到奖励积分");
		integral.setType(3);
		integralService.insertIntegral(integral);
		return ajax;
	}


	@ApiOperation("查询地址列表")
	@PostMapping("/getAddressList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getAddressList(@RequestParam long memberId,
									 @RequestParam int pageNum,
									 @RequestParam int pageSize) throws Exception{
		Address addr = new Address();
		addr.setMemberId(memberId);
		String orderBy = "create_time desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<Address> list = addressService.selectAddressList(addr);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("count", new PageInfo<Address>(list).getTotal());
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("新增地址")
	@PostMapping("/addAddress")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "realName", value = "姓名", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "telephone", value = "手机号", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query")

	})
	@ResponseBody
	public AjaxResult addAddress(@RequestParam String realName,
								 @RequestParam String telephone,
								 @RequestParam String address,
								 @RequestParam long memberId) throws Exception{

		Address addr = new Address();
		addr.setRealname(realName);
		addr.setTelephone(telephone);
		addr.setAddress(address);
		addr.setMemberId(memberId);
		AjaxResult ajax = AjaxResult.success();
		ajax.put("code", addressService.insertAddress(addr));
		ajax.put("data", addr);
		return ajax;
	}

	@ApiOperation("修改地址")
	@PostMapping("/editAddress")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "realName", value = "姓名", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "telephone", value = "手机号", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "address", value = "地址", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult editAddress(@RequestParam(value="realName", required=false) String realName,
								  @RequestParam(value="telephone", required=false) String telephone,
								  @RequestParam(value="address", required=false) String address,
								 @RequestParam long id) throws Exception{
		Address addr =  addressService.selectAddressById(id);
		if(StringUtils.isNotBlank(realName)){
			addr.setRealname(realName);
		}
		if(StringUtils.isNotBlank(telephone)){
			addr.setTelephone(telephone);
		}
		if(StringUtils.isNotBlank(address)){
			addr.setAddress(address);
		}
		AjaxResult ajax = AjaxResult.success();
		ajax.put("code", addressService.updateAddress(addr));
		ajax.put("data", addr);
		return ajax;
	}

	@ApiOperation("删除地址")
	@PostMapping("/deleteAddress")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult deleteAddress(@RequestParam long id) throws Exception{
		AjaxResult ajax = AjaxResult.success();
		ajax.put("code", addressService.deleteAddressById(id));
		return ajax;
	}

	@ApiOperation("查询新闻列表")
	@PostMapping("/getNewsList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "title", value = "标题", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "content", value = "正文", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getNewsList(@RequestParam(value="title", required=false) String title,
									@RequestParam(value="content", required=false) String content,
									@RequestParam(value="memberId", required=false) String memberId,
									@RequestParam int pageNum,
									@RequestParam int pageSize) throws Exception{
		News news = new News();
		if(StringUtils.isNotBlank(title)){
			news.setTitle(title);
		}
		if(StringUtils.isNotBlank(content)){
			news.setContent(content);
		}
		String orderBy = "publish_time desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<News> list = newsService.selectNewsList(news);
		if(StringUtils.isNotBlank(memberId)){
			Collect collect = new Collect();
			collect.setMemberId(Long.parseLong(memberId));
			for (News ns: list){
				collect.setNewsId(ns.getId());
				List<Collect> collectList = collectService.selectCollectList(collect);
				ns.setCollectFlag(collectList.size()>0?1:0);
			}
		}
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("count", new PageInfo<News>(list).getTotal());
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询新闻详情")
	@PostMapping("/findNews")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "新闻id", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),
	})
	@ResponseBody
	public AjaxResult findNews(@RequestParam long id,
							   @RequestParam(value="memberId", required=false) String memberId) throws Exception{
		News news = newsService.selectNewsById(id);
		if(StringUtils.isNotBlank(memberId)){
			Collect collect = new Collect();
			collect.setNewsId(id);
			collect.setMemberId(Long.parseLong(memberId));
			List<Collect> collectList = collectService.selectCollectList(collect);
			news.setCollectFlag(collectList.size()>0?1:0);
		}
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", news);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询收藏列表")
	@PostMapping("/getCollectList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "新闻标题", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getCollectList(@RequestParam long memberId,
									  @RequestParam(value="title", required=false) String title,
									  @RequestParam int pageNum,
									  @RequestParam int pageSize) throws Exception{
		Collect collect = new Collect();
		collect.setMemberId(memberId);
		if(StringUtils.isNotBlank(title)){
			collect.setTitle(title);
		}
		String orderBy = "create_time desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<Collect> list = collectService.selectCollectList(collect);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("count", new PageInfo<Collect>(list).getTotal());
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("新增收藏")
	@PostMapping("/addCollect")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "title", value = "新闻标题", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "newsId", value = "新闻id", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query")

	})
	@ResponseBody
	public AjaxResult addCollect(@RequestParam String title,
								  @RequestParam long newsId,
								  @RequestParam long memberId) throws Exception{

		Collect collect = new Collect();
		collect.setNewsId(newsId);
		collect.setMemberId(memberId);
		AjaxResult ajax = AjaxResult.success();
		List<Collect> colls = collectService.selectCollectList(collect);
		if(colls.size()>0){
			ajax.put("code", 0);
			return ajax;
		}
		collect.setTitle(title);
		ajax.put("code", collectService.insertCollect(collect));
		ajax.put("data", collect);
		return ajax;
	}

	@ApiOperation("删除收藏")
	@PostMapping("/deleteCollect")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "newsId", value = "新闻id", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult deleteCollect(@RequestParam long newsId,
									@RequestParam long memberId) throws Exception{
		Collect collect = new Collect();
		collect.setNewsId(newsId);
		collect.setMemberId(memberId);
		AjaxResult ajax = AjaxResult.success();
		List<Collect> colls = collectService.selectCollectList(collect);
		if(colls.size()<1){
			ajax.put("code", 0);
			return ajax;
		}
		ajax.put("code", collectService.deleteCollectById(colls.get(0).getId()));
		return ajax;
	}

	@ApiOperation("新增意见反馈")
	@PostMapping("/addFeedback")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "realname", value = "姓名", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "telephone", value = "手机号", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "content", value = "建议内容", required = true, dataType = "string", paramType = "query")

	})
	@ResponseBody
	public AjaxResult addFeedback(@RequestParam(value="realname", required=false) String realname,
								  @RequestParam(value="telephone", required=false) String telephone,
								  @RequestParam(value="memberId", required=false) String memberId,
								  @RequestParam String content) throws Exception{

		Feedback feedback = new Feedback();
		if(StringUtils.isNotBlank(realname)){
			feedback.setRealname(realname);
		}
		if(StringUtils.isNotBlank(telephone)){
			feedback.setTelephone(telephone);
		}
		feedback.setContent(content);
		if(StringUtils.isNotBlank(memberId)){
			feedback.setMemberId(Long.parseLong(memberId));
		}
		AjaxResult ajax = AjaxResult.success();
		ajax.put("code", feedbackService.insertFeedback(feedback));
		ajax.put("data", feedback);
		return ajax;
	}

	@ApiOperation("获取积分明细")
	@PostMapping("/getIntegralDetail")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "业务员Id", required = true, dataType = "string", paramType = "query"),
	})
	@ResponseBody
	public AjaxResult getIntegralDetail(@RequestParam long memberId) throws Exception{
		Integral integral = new Integral();
		integral.setMemberId(memberId);
		AjaxResult ajax = AjaxResult.success();
		List<Integral> integralList = integralService.selectIntegralList(integral);
		int sum = 0;
		int addTotay = 0;
		int addTotal = 0;
		for(Integral jf: integralList){
			sum += jf.getIntegralCount();
			if(jf.getIntegralCount()>0){
				addTotal += jf.getIntegralCount();
				if(DateUtils.isSameDay(jf.getCreateTime(), new Date())){
					addTotay += jf.getIntegralCount();
				}
			}
		}

		List<SysDictData> sysDictDataList = dictDataService.selectDictDataByType("integral_type");
		List<HashMap<String, Object>> dictList = new ArrayList<>();
		HashMap<String, Object> dictMap = null;
		for(SysDictData sysDictData: sysDictDataList){
			dictMap = new LinkedHashMap<>();
			sysDictData.getDictValue();
			dictMap.put("name", sysDictData.getDictLabel());
			integral.setType(Integer.parseInt(sysDictData.getDictValue()));
			PageHelper.orderBy("create_time desc");
			List<Integral> integralDictList = integralService.selectIntegralList(integral);
			int dictSum = 0;
			Integral dictIntegral = null;
			if(integralDictList.size()>0){
				dictIntegral = integralDictList.get(0);
				for(Integral djf: integralDictList) {
					dictSum += djf.getIntegralCount();
				}
			}
			dictMap.put("sum", dictSum);
			dictMap.put("integral", dictIntegral);
			dictList.add(dictMap);
		}

		HashMap<String, Object> data = new LinkedHashMap<>();
		data.put("sum", sum);
		data.put("addTotay", addTotay);
		data.put("addTotal", addTotal);
		data.put("dictList", dictList);
		ajax.put("data", data);
		return ajax;
	}

	@ApiOperation("查询消息列表")
	@PostMapping("/getMessageList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "title", value = "标题", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getMessageList(@RequestParam(value="title", required=false) String title,
									 @RequestParam(value="type", required=false) String type,
									 @RequestParam(value="memberId", required=false) String memberId,
									 @RequestParam int pageNum,
									 @RequestParam int pageSize) throws Exception{
		Message message = new Message();
		if(StringUtils.isNotBlank(title)){
			message.setTitle(title);
		}
		if(StringUtils.isNotBlank(type)){
			message.setType(Integer.parseInt(type));
		}
		if(StringUtils.isNotBlank(memberId)){
			message.setMemberId(Long.parseLong(memberId));
		}
		String orderBy = "create_time desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<Message> list = messageService.selectMessageList(message);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("count", new PageInfo<Message>(list).getTotal());
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询消息详情")
	@PostMapping("/findMessage")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "消息id", required = false, dataType = "string", paramType = "query"),
	})
	@ResponseBody
	public AjaxResult findMessage(@RequestParam long id) throws Exception{
		Message message = messageService.selectMessageById(id);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", message);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询海报列表")
	@PostMapping("/getPosterList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "title", value = "标题", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "status", value = "审核状态", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "int", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getPosterList(@RequestParam(value="title", required=false) String title,
									@RequestParam(value="status", required=false) String status,
									@RequestParam(value="memberId", required=false) String memberId,
									@RequestParam int pageNum,
									@RequestParam int pageSize) throws Exception{
		Poster poster = new Poster();
		if(StringUtils.isNotBlank(title)){
			poster.setTitle(title);
		}
		if(StringUtils.isNotBlank(status)){
			poster.setStatus(Integer.parseInt(status));
		}
		if(StringUtils.isNotBlank(memberId)){
			poster.setMemberId(Long.parseLong(memberId));
		}
		String orderBy = "sort asc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		List<Poster> list = posterService.selectPosterList(poster);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("count", new PageInfo<Poster>(list).getTotal());
			ajax.put("data", list);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询海报详情")
	@PostMapping("/findPoster")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "海报id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult findPoster(@RequestParam long id) throws Exception{
		Poster poster = posterService.selectPosterById(id);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", poster);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("添加海报")
	@PostMapping("/addPoster")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "title", value = "标题", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "cover", value = "图片", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = false, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult addPoster(@RequestParam(value="title", required=false) String title,
									@RequestParam String cover,
									@RequestParam(value="memberId", required=false) String memberId) throws Exception{
		Poster poster = new Poster();
		if(StringUtils.isNotBlank(title)){
			poster.setTitle(title);
		}
		poster.setStatus(0);
		poster.setSort(9);
		poster.setCover(cover);
		if(StringUtils.isNotBlank(memberId)){
			poster.setMemberId(Long.parseLong(memberId));
		}
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("code", posterService.insertPoster(poster));
			ajax.put("data", poster);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("删除海报")
	@PostMapping("/deletePoster")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "海报id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult deletePoster(@RequestParam long id) throws Exception{
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("code", posterService.deletePosterById(id));
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询客户动态")
	@PostMapping("/getCustomerNews")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "beginDate", value = "开始日期", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "memberId", value = "业务员id", required = true, dataType = "string", paramType = "query")
	})
	@ResponseBody
	public AjaxResult getCustomerNews(@RequestParam(value="beginDate", required=false) String beginDate,
									  @RequestParam(value="endDate", required=false) String endDate,
									  @RequestParam String memberId) throws Exception{
		Map<String, Object> params = new LinkedHashMap<>();
		Customer customer = new Customer();
		customer.setMemberId(Long.parseLong(memberId));
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		customer.setParams(params);
		Integer count = customerService.selectCustomerCount(customer);
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", count);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation("查询appid和secret")
	@PostMapping("/getAsData")
	@ApiImplicitParams({
	})
	@ResponseBody
	public AjaxResult getAs() throws Exception{
		Map<String, Object> dataMap = new LinkedHashMap<>();
		dataMap.put("appid", "wxd24f26791e8f1a05");
		dataMap.put("secret", "526f8e5ab67d261cd07746e547dc286f");
		try{
			AjaxResult ajax = AjaxResult.success();
			ajax.put("data", dataMap);
			return ajax;
		}catch (Exception e){
			return AjaxResult.error(e.getMessage());
		}
	}

}
